/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : May 13, 2012  10:57:11 AM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.sd.outbound
 * File Name : SdChargecodeService.java
 * TODO
 */
package sap.business.sd.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.SdChargecode;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.SdChargecodeServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class SdChargecodeService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(SdChargecodeService.class);
	private SdChargecodeServices SdChargecodeServ;
	
	/**
	 * 
	 */
	public SdChargecodeService() {
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	private JCoTable ChargeCode(List<?> value_list) throws Exception {
		JCoTable jcoTable = jco_conn.getTables(this.sap_table);
		try{
			
			if(!jcoTable.isEmpty())
			{
				System.out.println("Bapi = "+ sap_bapi +", table : "+ sap_table +" is not Empty ");
				return null;
			}
			
			jcoTable.deleteAllRows();
			if(!CommonService.IsNull(value_list)){
				System.out.println("value_list.size : " + value_list.size() + " //table.getNumRows : " + jcoTable.getNumRows());
				
				for (Object obj : value_list)
		        {
					SdChargecode model = (SdChargecode)obj;
					System.out.println("InstanceNo = " + model.getInstanceNo() + " getDocumentNo = " + model.getDocumentNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " Charge Code : "+ model.getChargeCode());
					
					jcoTable.appendRow();
					jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
					jcoTable.setValue("ITM_CODE", model.getChargeCode());
					jcoTable.setValue("PRICE_AMOUNT", model.getReceivedAmt());
					jcoTable.setValue("CURRENCY", model.getCurrency());
					jcoTable.setValue("DUE_DATE", model.getReceivedDate());
					jcoTable.setValue("REFUND_AMT", CommonService.IsNullRZero(model.getRefundAmt()));
					jcoTable.setValue("STATUS", model.getStatus());
		        }
			}			
			
		}catch(Exception e)
		{
			e.printStackTrace();
			log.error(e.getMessage());
			throw e;
		}		
		return jcoTable;
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoStructure jCoStructure, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		
		if(CommonService.IsNull(value_list))
		{
			System.out.println("Bapi = "+ sap_bapi +", Structure : "+ sap_structure +" is not Empty ");
			return;
		}

		try{
			
			if(!CommonService.IsNull(value_list))
			{
				System.out.println("value_list size : " + CommonService.getSize(value_list));
				
				SdChargecode value = (SdChargecode)value_list.get(0);				
				jCoStructure.clear();
				jCoStructure.setValue("INTERFACE_NO", "SDI07");
				jCoStructure.setValue("PROMIS_DOCNO", value.getDocumentNo());				
				jCoStructure.setValue("PLANT_CODE", value.getSapPlantCode());
				
				ChargeCode(value_list);
			}
			
			super.SynchroToSap(jcoFunction, jCoStructure, value_list);
			
		}catch(Exception e)
		{
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		
		try{
			
			List<SdChargecode> lst = new ArrayList<SdChargecode>();				
			if(!jcoTable_return.isEmpty())
			{
				System.out.println("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
				for(int i = 0; i < jcoTable_return.getNumRows(); i++)
				{
					jcoTable_return.setRow(i);			
					SdChargecode model = SdChargecodeServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
					System.out.println(CommonJCOReturn.toString(jcoTable_return));
					
					if(model != null){
						model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
						model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
						model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
						model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
						model.setIsactive("Y");
						model.setIssync("Y");
						
						lst.add(model);
					}
				}
				
				if(!CommonService.IsNull(lst)){				
					SdChargecodeServ.Updated(lst);
					System.out.println("Update Staging CallbackMessageFromSap size : " + lst.size());
				}
			}else
				System.out.println(CommonJCOReturn.toString(jcoTable_return));
			
			super.CallbackMessageFromSap(jcoTable_return);
			
		}catch(Exception e)
		{
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}		
	}
	
	private void UpdateStagingWhenError(List<SdChargecode> value_list, Exception error) throws Exception{
		System.out.println("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<SdChargecode> newlst = new ArrayList<SdChargecode>();
				for(SdChargecode model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new SdChargecodeServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			System.out.println("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendingToSAP(List<SdChargecode> value_list) throws Exception 
	{
		System.out.println("SendingToSAP Start ==================> ");
		try{			
			if(!CommonService.IsNull(value_list))
			{
				
				this.sap_bapi = "ZIN_SD_CHARGECODE_PROCESSING";			
				this.sap_structure = "HEADER";
				this.sap_table = "CHARGE_CODE";						
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
				
				SdChargecodeServ = new SdChargecodeServices(this.emSynchro);
				

				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table Header
				//JCoTable jcoTable = jco_conn.getTables(sap_table);
				JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
						
				//List<SdCustoRequDeducOutb> value_list = SdCustoRequDeducOutbServ.findAllIsSync("N");
				
				SynchroToSap(jcoFunction, jCoStructure, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
				
			}
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);
			e.printStackTrace();			
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
}
